package org.example.leetcode.addon.lc39;

import java.util.Deque;
import java.util.LinkedList;
import java.util.List;

public class Solution {
    List<List<Integer>> ans = new LinkedList<>();
    Deque<Integer> condition = new LinkedList<>();

    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        if (candidates == null || candidates.length == 0) {
            return ans;
        }
        backtracking(candidates, target, 0, 0);

        return ans;
    }

    private void backtracking(int[] candidates, int target, int sum, int startIndex) {
        if (sum > target) return;
        if (sum == target) ans.add(new LinkedList<>(condition));

        for (int i = startIndex; i < candidates.length; i++) {
            sum += candidates[i];
            condition.add(candidates[i]);
            backtracking(candidates, target, sum, i);
            sum -= candidates[i];
            condition.removeLast();
        }
    }
}
